<?php

namespace App\Http\Middleware;

use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\WaiMai\Enum\ElmWaiMaiEnum;
use App\Kuafu\WaiMai\Model\WaiMaiCallbackLogModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use App\Kuafu\WaiMai\Service\WaiMaiShopService;
use Closure;
use Illuminate\Support\Facades\Log;

class ElmWaiMaiCheckSign
{
    private $sourceType = CodeEnum::SOURCE_TYPE_ELM;

    /**
     * 饿了么外卖回调接口 - 日志、校验签名
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 日志入库
        $message     = $request->get('message', '');
        $messageArr  = json_decode($message, true);
        $orderId     = (int)($messageArr['orderId'] ?? 0);
        if (!$orderId) {
            $orderId = (int)($messageArr['id'] ?? 0);
        }

        $thirdShopId = (string)$request->get('shopId', '');
        $type        = $request->get('type', '');
        $route       = $request->getPathInfo() . '?type=' . $type;

        // 请求数据为空的，直接返回
        if (!$request->all()) {
            return response()->json(['message' => 'ok'])->header('Content-Type', 'application/json;charset=utf-8');
        }

        // 未绑定的店铺不入库
        $shopId =  WaiMaiShopService::getThirdMappingCache($thirdShopId, $this->sourceType);
        if (!$shopId) {
            Log::channel('waiMai')->info("Elm Filter Unbind Store: {$thirdShopId} {$route}");
            return response()->json(['message' => 'ok'])->header('Content-Type', 'application/json;charset=utf-8');
        }

        // 10不处理，太占硬盘了
        if ($type == ElmWaiMaiEnum::TYPE_10) {
            return response()->json(['message' => 'ok'])->header('Content-Type', 'application/json;charset=utf-8');
        }

        BaseWaiMaiOrderService::$callBackShopId = $shopId;
        BaseWaiMaiOrderService::$callBackId = WaiMaiCallbackLogModel::addData($this->sourceType, $orderId,
            $thirdShopId, json_encode($request->all()), $route, $shopId);

        return $next($request);
    }
}
